// web/src/app/learn/(course)/courses/[courseId]/chapters/[chapterId]/_components/course-progress-button.tsx
'use client';
import React, {useState} from 'react';
import {Button} from "@/components/ui/button";
import {CheckCircle, XCircle} from "lucide-react";
import {useRouter} from "next/navigation";
import {useConfettiStore} from "@/hooks/learn/use-confetti-store";
import toast from "react-hot-toast";

interface Props {
    chapterId: string
    courseId: string
    nextChapterId?: string
    isCompleted?: boolean
}

// 点击确认完成该章节, 跳转下章
const CourseProgressButton = ({
                                  courseId, chapterId, nextChapterId, isCompleted
                              }: Props) => {
    const router = useRouter()
    const confetti = useConfettiStore()
    const [isLoading, setIsLoading] = useState(false)

    const onClick = async () => {
        try {
            setIsLoading(true)

            const res = await fetch(`/api/course/${courseId}/chapters/${chapterId}/progress`,
                {
                    method: "PUT",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({isCompleted: !isCompleted}),
                })
            if (!res.ok) throw new Error(`Failed to fetch`)

            if (!isCompleted && !nextChapterId) {
                confetti.onOpen()
            }

            toast.success(`Progress updated`)
            router.refresh()

            if (!isCompleted && nextChapterId) {
                router.push(`/learn/courses/${courseId}/chapters/${nextChapterId}`)
            }
        } catch (err) {
            toast.error(`Something went wrong`)
        } finally {
            setIsLoading(false)
        }
    }

    const Icon = isCompleted ? XCircle : CheckCircle

    return (
        <Button
            onClick={onClick}
            disabled={isLoading}
            type="button"
            className={`w-full md:w-auto`}
            variant={isCompleted ? 'outline' : 'success'}
        >
            {isCompleted ? 'Not completed' : 'Mark as complete'}
            <Icon className={`size-4 ml-2`}/>
        </Button>
    );
};

export default CourseProgressButton;